package com.zhuhjay.common.web.util;

import cn.hutool.extra.servlet.ServletUtil;
import com.zhuhjay.common.base.model.vo.HttpResult;
import com.zhuhjay.common.base.util.JacksonUtils;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author ZhuHJay
 * @date 2023/2/25 0:57
 */
public class ServletUtils {

    /** 获取当前的 request **/
    public static HttpServletRequest currentRequest() {
        return ((ServletRequestAttributes) Objects
                .requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

    /** 获取当前的 response **/
    public static HttpServletResponse currentResponse() {
        return ((ServletRequestAttributes) Objects
                .requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse();
    }

    public static void writeToJson(HttpServletResponse response, HttpResult<?> result) {
        ServletUtil.write(response, JacksonUtils.writeValueAsString(result), MediaType.APPLICATION_JSON_UTF8_VALUE);
    }

}
